﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Chefbook.DataObjects.XmlSerialization
{
    public static class CategoryXmlSerializer
    {
        public const string Root = "Root";
        public const string Category = "Category";
        public const string Recipe = "Recipe";
        public const string Name = "Name";


        public static XDocument SerializeCategories(IEnumerable<Category> root)
        {
            XElement rootXml = new XElement(Root);
            foreach (var item in root)
            {
                rootXml.Add(SerializeSubs(item));
            }
            XDocument xml = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"));
            xml.Add(rootXml);
            return xml;

        }

        public static IEnumerable<Category> DeserializeCategories(XDocument xml)
        {
            List<Category> rootCategories = new List<Category>();
            var p = from r in xml.Root.Elements(Category)
                    select r;
            foreach (var xmlCat in p)
            {
                rootCategories.Add(DeserializeSubs(xmlCat, null));
            }
            return rootCategories;
        }

        private static Category DeserializeSubs(XElement element, Category parent)
        {
            Category thisCat = new Category(parent) { Name = element.Attribute(Name).Value };
            foreach (var recipeXml in element.Elements(Recipe))
            {
                new Recipe(thisCat) { Name = recipeXml.Attribute(Name).Value };   
            }
            foreach (var categoryXml in element.Elements(Category))
            {
                DeserializeSubs(categoryXml, thisCat);
            }
            return thisCat;
        }

        private static XElement SerializeSubs(Category category)
        {
            XElement catElement = new XElement(Category, new XAttribute(Name, category.Name));
            foreach (var recipe in category.DirectRecipes)
            {
                catElement.Add(
                    new XElement(Recipe, 
                        new XAttribute(Name, recipe.Name)));
            }
            foreach (var sub in category.Subcategories)
            {
                catElement.Add(SerializeSubs(sub));
            }
            return catElement;

        }
    }
}
